package thread;

public class SyncDemo {//多线程并发安全问题(防止大家抢同一个资源)

    public static void main(String[] args) {
        Table table = new Table();
        Thread t1 = new Thread("甲") {
            public void run() {
                while (true) {
                    int bean = table.getBeans();
                    Thread.yield();
                    System.out.println(getName() + ":" + bean);
                }
            }
        };

        Thread t2 = new Thread("乙") {
            public void run() {
                while (true) {
                    int bean = table.getBeans();
                    Thread.yield();
                    System.out.println(getName() + ":" + bean);
                }
            }
        };
        t1.start();
        t2.start();

    }

}

class Table {
    private int beans = 20;//桌子上有20个豆子
    //synchronized关键词,让对象调用方法时执行完毕才能被其他线程调用(办事之前先锁门)
    public synchronized int getBeans() {
        if (beans == 0) {
            throw new RuntimeException("豆子没了");
        }
        Thread.yield();
        //使用放弃时间片来模拟线程到此时没有时间线了
        //运行该方法的线程放弃本次剩余时间
        return beans--;
    }
}